import { ElementRef, EventEmitter, Input, Output, ViewChild, Directive } from '@angular/core';
import {ObjectUtil} from '../../utils/object-util';
import {DhlCommonComponent} from './dhlCommonComponent';


@Directive()
export class DhlCommonInputComponent extends DhlCommonComponent {


  inputWidth;
  inputValue = [];
  labelWidthInner = 0;
  defaultValue;
  @Input() name = '';

  @Input()
  set value(value) {
    this.valueInit(value);
    this.afterInitValue(value);
  };

  get value() {
    return this.inputValue;
  }

  @Input() code = '';

  @Input()
  set labelWidth(value) {
    this.inputWidth = value < 24 ? 24 - value : 1;
    this.labelWidthInner = value;
  };

  get labelWidth() {
    return this.labelWidthInner;
  }

  @Input() required = false;
  @Input() disabled = false;
  @Output() valueChange = new EventEmitter();
  @Input() onValueChange;
  @ViewChild('inputControl', {static: true, read: ElementRef}) inputControl: ElementRef;


  constructor() {
    super();
    setTimeout(() => {
      if (ObjectUtil.isHaveValue(this.inputControl)) {
        $('input', this.inputControl.nativeElement).attr('name', this.code);
      }
    }, 100);
  }

  valueInit(value) {
    if (ObjectUtil.isHaveValue(value)) {
      if (!ObjectUtil.isHaveValue(this.defaultValue)) {
        this.defaultValue = value;
      }
      if (value == '#EMPTY') {
        this.inputValue = undefined;
      } else {
        this.inputValue = value;
      }
    } else {
      this.defaultValue = '#EMPTY';
    }
  }

  afterInitValue(value) {

  }

  reset() {
    if (this.defaultValue == '#EMPTY') {
      if (this.inputValue) {
        this.valueChange.emit();
      }
      this.inputValue = undefined;
    } else {
      if (this.inputValue != this.defaultValue) {
        this.valueChange.emit(this.inputValue);
      }
      this.inputValue = this.defaultValue;
    }
  }

}
